# 玩家角色控制脚本
extends CharacterBody2D
# 玩家移动速度
var speed = 300
# 动画精灵组件
@onready var animated_sprite = $AnimatedSprite2D
# 背包UI组件
@onready  var backpack = $Camera2D/BackPack
# 导出的背包资源引用
@export var inventory: Inventory 

# 初始化：隐藏背包
func _ready() -> void:
	backpack.visible = false
# 物理处理：移动和动画更新
func _physics_process(delta: float) -> void:
	var direction = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")	
	velocity = direction * speed
	move_and_slide()
	update_animation(direction)
	# 背包开关控制
	if Input.is_action_just_pressed("backpack"):
		if backpack.visible == false:
			backpack.visible = true
		else:
			backpack.visible = false
# 更新角色动画
func update_animation(direction: Vector2) -> void:
	if direction == Vector2.ZERO:
		if animated_sprite.animation != "default":
			animated_sprite.play("default")
		return
	# 根据移动方向播放对应动画
	if direction.x != 0:
		if direction.x < 0:
			animated_sprite.play("left")
		else:
			animated_sprite.play("right")
	elif direction.y != 0:
		if direction.y < 0:
			animated_sprite.play("up")
		else :
			animated_sprite.play("down")
		
# 收集物品函数：将物品添加到背包
func collect(item):
	inventory.insert(item)
